<?php

namespace App\Admin\Controllers\fund;

use App\Admin\Actions\Row\TableActions;
use App\Admin\Renderable\AdminGroupTable;
use App\Admin\Renderable\FundNewsTable;
use App\Admin\Renderable\UserTable;
use App\Models\AdminCharityFund;
use App\Models\AdminUserGroup;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Card;

class ListController extends AdminController
{
    protected $title = "基金";

    protected $translation = 'admin-charity-fund';
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(AdminCharityFund::with(['admin','user']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('cover_path') -> image('','100');
            $grid->column('info','基本信息') -> display(
                function(){
                    return <<<HTML
                       <div style="line-height: 1.8; font-size: 14px; text-align: left;">
                            <div><strong>标题：</strong> {$this->title}</div>
                            <div><strong>发布人：</strong> {$this->admin->name} - {$this->admin->phone}</div>
                            <div><strong>负责人：</strong> {$this->user->name} - {$this->user->phone}</div>
                        </div>
                    HTML;
                }
            );
            $grid->column('other','项目信息') -> display(
                function(){
                    return <<<HTML
                       <div style="line-height: 1.8; font-size: 14px; text-align: left;">
                            <div><strong>已筹：</strong> {$this->target_amount}</div>
                            <div><strong>目标：</strong> {$this->target_amount}</div>
                            <div><strong>划拨：</strong> {$this->target_amount}</div>
                        </div>
                    HTML;
                }
            );
            $grid->column('content') -> display('查看') -> modal(
                function ($modal) {
                    $modal->title($this->title);
                    $content = <<<HTML
                        <div class="rich-content">
                            {$this->content}
                        </div>
                        <style>
                            .rich-content {
                                width: 100%;
                                word-break: break-word;
                            }
                            .rich-content img {
                                max-width: 100%;
                                height: auto;
                                display: block;
                            }
                        </style>
                    HTML;
                    $card = new Card(null, $content);
                    return "<div style='padding:10px 10px 0'>$card</div>";
                }
            );
            $grid->column('online_status') -> switch();
            $grid->showEditButton();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableQuickEdit();
                $actions->append(new TableActions(FundNewsTable::class));
            });
            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->selectOne('online_status', '上线状态', ['已下线', '已上线']);
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AdminCharityFund(), function (Form $form) {
            $form->title('编辑基金');
            $form -> disableDeleteButton();
            $form -> disableViewButton();
            $form -> disableResetButton();
            $form
                ->tab('基本信息', fn($form) => $this -> firstFrom($form))
                ->tab('选填信息', fn($form) => $this -> secondFrom($form))
                ->tab('基金详情', fn($form) => $this -> thirdFrom($form));

            $form -> saving(function (Form $form) {
                $data = $form -> input();

                $data['id'] = $form -> model() -> id;

                $model = AdminCharityFund::find($data['id']);

                if(key_exists('random_donation_amount', $data)) {
                    $data['random_donation_amount'] = $data['random_donation_amount'] ?? '0';
                }

                if(key_exists('personal_donation_amount_type', $data)) {
                    $data['personal_donation_amount'] = implode(',', setDonationAmounts($data, 'personal'));
                }

                if(key_exists('corporate_donation_amount_type', $data)) {
                    $data['corporate_donation_amount'] = implode(',', setDonationAmounts($data, 'corporate'));
                }

                if(key_exists('administrative_committee', $data) && $data['administrative_committee']) {
                    $filtered = collect($data['administrative_committee'])
                        ->filter(fn($item) => empty($item['_remove_']) || $item['_remove_'] == '0')
                        ->map(function ($item) {
                            unset($item['_remove_']);
                            return $item;
                        })
                        ->values();
                    $data['administrative_committee'] = json_encode($filtered, JSON_UNESCAPED_UNICODE);
                }

                $res = $model->update($data);

                if(!$res) {
                    return $form -> response() -> error('操作失败');
                }

                return $form -> response() ->success('操作成功') -> redirect('/fund/list');
            });
        });
    }


    public function firstFrom($form)
    {
        $form->text('title')
            ->required();

        $form->textarea('description')
            ->required();

        $form->radio('charity_fund_type')
            ->options(fn () => trans('admin-charity-fund.options.charity_fund_type'))
            ->default(0)
            ->required();

        $form->radio('use_type')
            ->options(fn () => trans('admin-charity-fund.options.use_type'))
            ->default(0)
            ->required();

        $form->dateRange('start_time', 'end_time', '筹款时间')
            ->required();

        $map_data = [
            'name'      => 'address',
            'address'   => $form->model()->address,
            'longitude' => $form->model()->longitude,
            'latitude'  => $form->model()->latitude
        ];

        $form->number('target_amount');

        $form->html(view('admin.components.map-dialog', $map_data)->render(),'项目地址')
            ->required();

        $donation_amount_data_3 = [
            'name'          => 'personal_donation_amount_3',
            'default_values' => [20, 50, 100],
            'init_values'    => ['','',''],
            'personal_donation_amount_type' => 0
        ];

        $donation_amount_data_6 = [
            'name'          => 'personal_donation_amount_6',
            'default_values' => [20, 50, 100, 200, 500, 1000],
            'init_values'    => ['','','','','',''],
            'personal_donation_amount_type' => 1
        ];

        $personal_donation_amount_type = 0;

        if($form->model()->personal_donation_amount) {
            $init_personal_values = explode(',', $form->model()->personal_donation_amount);
            if(count($init_personal_values) === 3) {
                $personal_donation_amount_type = 0;
                $donation_amount_data_3['init_values'] = $init_personal_values;
            } else {
                $personal_donation_amount_type = 1;
                $donation_amount_data_6['init_values'] = $init_personal_values;
            }
        }

        $form->radio('personal_donation_amount_type','个人捐款选项')
            ->when(0, function ($form) use ($donation_amount_data_3) {
                $form->html(view('admin.components.donation-amount', $donation_amount_data_3)->render());
            })
            ->when(1, function ($form) use ($donation_amount_data_6) {
                $form->html(view('admin.components.donation-amount', $donation_amount_data_6)->render());
            })
            ->options([
                0 => '三个选项',
                1 => '六个选项'
            ])
            ->value($personal_donation_amount_type)
            ->required();

        $corporate_donation_amount_3 = [
            'name'          => 'corporate_donation_amount_3',
            'default_values' => [20, 50, 100],
            'init_values'    => ['','','']
        ];
        $corporate_donation_amount_6 = [
            'name'          => 'corporate_donation_amount_6',
            'default_values' => [20, 50, 100, 200, 500, 1000],
            'init_values'    => ['','','','','','']
        ];

        $corporate_donation_amount_type = 0;

        if($form->model()->corporate_donation_amount) {
            $init_corporate_values = explode(',', $form->model()->corporate_donation_amount);
            if(count($init_corporate_values) === 3) {
                $corporate_donation_amount_type = 0;
                $corporate_donation_amount_3['init_values'] = $init_corporate_values;
            } else {
                $corporate_donation_amount_type = 1;
                $corporate_donation_amount_6['init_values'] = $init_corporate_values;
            }
        }

        $form->radio('corporate_donation_amount_type','企业捐款选项')
            ->when(0, function ($form) use($corporate_donation_amount_3) {
                $form->html(view('admin.components.donation-amount', $corporate_donation_amount_3)->render());
            })
            ->when(1, function ($form) use($corporate_donation_amount_6) {
                $form->html(view('admin.components.donation-amount', $corporate_donation_amount_6)->render());
            })
            ->options([
                0 => '三个选项',
                1 => '六个选项'
            ])
            ->value($corporate_donation_amount_type)
            ->required();

        $form->text('random_donation_amount')
            ->help('随缘捐选项配置说明：请输入项目捐赠随缘捐选项，用英文逗号隔开，例如：6.6,8.8,10,16.6,20,28.8,36.6,52,88.8,如输入0则关闭随缘捐');

        $form->selectTable('user_id')
            ->from(UserTable::make(['id' => $form->getKey()]))
            ->model(User::class, 'id', 'name')
            ->required();

        $form->selectTable('group_id')
            ->from(AdminGroupTable::make(['id' => $form->getKey()]))
            ->model(AdminUserGroup::class, 'id', 'name')
            ->required();

        $form->image('cover_path')
            ->url('/project/common/upload')
            ->autoUpload()
            ->maxSize(5120)
            ->required();
    }

    public function secondFrom($form)
    {
        $form->text('registration_number');
        $form->text('fund_code');
        $form->table('administrative_committee',function (NestedForm $table) {
            $table->text('position','职务');
            $table->text('name','姓名');
        });
        $form->radio('donation_type') -> options(trans('admin-charity-fund.options.donation_type')) -> default(0);
        $form->switch('online_status');
        $form->switch('donate_together');
    }

    public function thirdFrom($form)
    {
        $form->editor('content')->required();
    }
}
